package com.yylany.auth.controller;


import com.yylany.auth.config.JwtProperties;
import com.yylany.auth.entity.UserInfo;
import com.yylany.auth.service.AuthService;
import com.yylany.auth.util.JwtUtils;
import com.yylany.enums.ResultEnum;
import com.yylany.pojo.TbUser;
import com.yylany.vo.BaseResult;
import com.yylany.vo.LoginResult;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * Description: 用户的前台接口
 *
 * @author <a href="mailto:17777502615@163.com">yaoyonglong</a>
 * @date 2018/12/17
 * @since 1.0.0
 */

/**
 * Description: 用户的前台接口
 *
 * @author <a href="mailto:17777502615@163.com">yaoyonglong</a>
 * @date 2018/12/17
 * @since 1.0.0
 */
@RestController
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private JwtProperties prop;

    @Autowired
    private HttpServletRequest req;

    /***
     * ** 验证用户信息 *
     * @return* **/
    @GetMapping("verify")
    public ResponseEntity<UserInfo> verifyUser() {
        try {
            String token = req.getHeader("Authorization");
            // 获取token信息
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, prop.getPublicKey());
            // 成功后直接返回
            return ResponseEntity.ok(userInfo);
        } catch (Exception e) {
            // 抛出异常，证明token无效，直接返回401
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(null);
        }
    }


    /**
     * 登录
     *
     * @param user
     * @return
     */
    @PostMapping("/login")
    public ResponseEntity<Object> login(@RequestBody TbUser user) {

        // 登录校验生成token
        LoginResult token = this.authService.login(user.getMobile(), user.getPassword());
        if (token == null) {
            // 登录失败
            BaseResult br = new BaseResult(ResultEnum.LOGIN_MSG.getErrno(), ResultEnum.LOGIN_MSG.getErrmsg());
            return ResponseEntity.ok(br);
        }
        // 返回token
        token.setErrno(ResultEnum.LOGIN_SUCCESS.getErrno());
        token.setErrmsg(ResultEnum.LOGIN_SUCCESS.getErrmsg());
        return ResponseEntity.ok(token);
    }

}
